use std::time::Duration;

use reqwest::Client;

use crate::models::Response;

pub struct RequestModel {
    base_url: &'static str,
    client: Client,
}

impl RequestModel {
    pub fn new(base_url: &'static str) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(5))
            .pool_idle_timeout(Duration::from_secs(30))
            .tcp_keepalive(Duration::from_secs(60))
            .build()
            .expect("Failed to create HTTP client");

        RequestModel { base_url, client }
    }

    pub async fn send(&self, url: String) -> Result<Response, ()> {
        match self
            .client
            .get(format!("{}{}", self.base_url, url))
            .send()
            .await
        {
            Ok(response) => {
                let data = response.json::<Response>().await.unwrap();
                Ok(data)
            }
            Err(err) => {
                println!("error: {:?}", err);
                Err(())
            }
        }
    }

}

#[cfg(test)]
mod test {

    use crate::{models::Response, request::RequestModel};

    #[tokio::test]
    pub async fn test_request() {
        let request = RequestModel::new("http://127.0.0.1:8080");

        let mut response = request.send("/api/v1/device/register/2".to_owned()).await.unwrap();
        assert_eq!(Response { status: true }, response);
        response = request.send("/api/v1/device/status/2".to_owned()).await.unwrap();
        assert!(!response.is_permited());
    }
}
